import Mn from 'backbone.marionette';
import PaymentDepositView from './PaymentDepositView.js';
import PaymentLineModel from '../../models/PaymentLineModel.js';
import PaymentLineCollectionView from './PaymentLineCollectionView.js';
import PaymentLineFormView from './PaymentLineFormView.js';
import Radio from 'backbone.radio';
import {
    strToFloat
} from '../../../math.js';
import ButtonWidget from '../../../widgets/ButtonWidget.js';

const PaymentLineTableView = Mn.View.extend({
    template: require('./templates/PaymentLineTableView.mustache'),
    regions: {
        lines: {
            el: '.paymentlines',
            replaceElement: true
        },
        modalRegion: '.payment-line-modal-container',
        deposit: ".deposit",
        addbutton: '.addbutton'
    },
    modelEvents: {
        'changed:payment_times': 'onPaymentTimesChanged',
        'saved:payment_times': 'onPaymentTimesChanged',
        'saved:deposit': 'showDeposit',
        'saved:paymentDisplay': 'render'
    },
    childViewEvents: {
        'line:edit': 'onLineEdit',
        'line:delete': 'onLineDelete',
        'order:up': 'onModelOrderUp',
        'order:down': 'onModelOrderDown',
        'destroy:modal': 'render',
        'add:duedate': 'onLineAdd'
    },
    initialize(options) {
        this.collection = options['collection'];
        this.message = Radio.channel('message');
    },
    onPaymentTimesChanged(value) {

        this.showAddButton();
        this.showDeposit();
    },
    onLineAdd() {
        var model = new PaymentLineModel({
            task_id: this.model.get('id'),
            order: this.collection.getMaxOrder() - 1,
        });
        this.showPaymentLineForm(model, "Ajouter une échéance", false);
    },
    onLineEdit(childView) {
        this.showPaymentLineForm(childView.model, "Modifier l’échéance", true);
    },
    onModelOrderUp: function (childView) {
        this.collection.moveUp(childView.model);
    },
    onModelOrderDown: function (childView) {
        this.collection.moveDown(childView.model);
    },
    showPaymentLineForm: function (model, title, edit) {
        let edit_amount = false;
        if (this.model.isAmountEditable()) {
            edit_amount = true;
            if (edit) {
                if (model.isLast()) {
                    edit_amount = false;
                }
            }
        }
        var form = new PaymentLineFormView({
            model: model,
            title: title,
            destCollection: this.collection,
            edit: edit,
            edit_amount: edit_amount,
            show_date: this.model.isDateEditable(),
        });
        this.showChildView('modalRegion', form);
    },
    onDeleteSuccess() {
        this.message.trigger('success', "Vos données ont bien été supprimées");
        this.collection.fetch({
            success: () => this.model.fetch()
        });
    },
    onDeleteError() {
        this.message.trigger(
            'error',
            "Une erreur a été rencontrée lors de la suppression de cet élément"
        );
        this.collection.fetch();
    },
    onLineDelete(childView) {
        var result = window.confirm(
            "Êtes-vous sûr de vouloir supprimer cette échéance ?"
        );
        if (result) {
            childView.model.destroy({
                success: this.onDeleteSuccess.bind(this),
                error: this.onDeleteError.bind(this),
            });
        }
    },
    templateContext() {
        return {
            show_date: this.model.isDateEditable(),
            show_add: this.model.isAmountEditable(),
        };
    },
    showDeposit() {
        const deposit = strToFloat(this.model.get('deposit'));
        if (deposit > 0) {
            var view = new PaymentDepositView({
                model: this.model,
                show_date: this.model.isDateEditable(),
            });
            this.showChildView('deposit', view);
        } else {
            this.getRegion('deposit').empty();
        }
    },
    showLines() {
        this.showChildView(
            'lines',
            new PaymentLineCollectionView({
                collection: this.collection,
                show_date: this.model.isDateEditable(),
                edit: this.model.isAmountEditable(),
            })
        );
    },
    showAddButton() {
        if (this.model.isAmountEditable()) {
            const widget = new ButtonWidget({
                label: "Ajouter une échéance",
                icon: "plus",
                event: "add:duedate",
                css: 'btn-info'
            })
            this.showChildView('addbutton', widget);
        } else {
            this.getRegion('addbutton').empty();
        }
    },
    onRender() {
        this.showDeposit();
        this.showLines();
        this.showAddButton();
    },
});
export default PaymentLineTableView;
